import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'

import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import { loadEnv } from './src/utils/vite'
import type { UserConfig, ConfigEnv, ProxyOptions } from 'vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

// https://vitejs.dev/config/
const viteConfig = ({ mode }: ConfigEnv): UserConfig => {
    const { VITE_PROXY_URL, VITE_BASE_PATH } = loadEnv(mode)
    let proxy: Record<string, string | ProxyOptions> = {}
    if (VITE_PROXY_URL) {
        proxy = {
            '^/api': {
                target: VITE_PROXY_URL,
                changeOrigin: true,
                rewrite: (path) => path.replace(/^\/api/, ''), // 将/api替换为空
            },
        }
    }
    return defineConfig({
        base: VITE_BASE_PATH,
        plugins: [
            vue(),
            AutoImport({
                dts: 'types/auto-imports.d.ts',
                resolvers: [
                    ElementPlusResolver({
                        // 自动引入修改主题色添加这一行，使用预处理样式，不添加将会导致使用ElMessage，ElNotification等组件时默认的主题色会覆盖自定义的主题色
                        importStyle: 'sass',
                    }),
                ],
                imports: [
                    // 'vue',
                    // 'vue-router',
                    {
                        '@/hooks': ['useMessage', 'useMessageBox'],
                        '@/locales': ['$t'],
                    },
                ],
            }),
            Components({
                dts: 'types/components.d.ts',
                resolvers: [
                    ElementPlusResolver({
                        // 自动引入修改主题色添加这一行，使用预处理样式
                        importStyle: 'sass',
                    }),
                ],
            }),
        ],
        resolve: {
            alias: {
                '@': fileURLToPath(new URL('./src', import.meta.url)),
            },
        },
        css: {
            preprocessorOptions: {
                // 引入公用的样式
                scss: {
                    additionalData: '@use "@/styles/element.scss" as *;',
                },
            },
        },
        server: {
            host: '0.0.0.0',
            // port: 5174,
            open: false,
            proxy: proxy,
        },
    })
}

export default viteConfig
